package org.cy.spring.learning.rpc.client;

import org.cy.spring.learning.rpc.comm.network.NetworkClient;
import org.cy.spring.learning.rpc.comm.network.Request;
import org.cy.spring.learning.rpc.comm.network.SocketClient;
import org.cy.spring.learning.rpc.comm.protocols.Protocol;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 代理调用实现
 *
 * create date: 2019/10/18 12:16
 *
 * @author cao.yong
 */
public class ClientRemoteInvokeHandler implements InvocationHandler {

    private Class<?> clazz;
    private Map<String, Protocol> protocols = new HashMap<>(0);
    private NetworkClient networkClient = new SocketClient();

    ClientRemoteInvokeHandler(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Request request = new Request();
        request.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        request.setServiceName(clazz.getName());
        request.setMethodName(method.getName());
        request.setParameterTypes(method.getParameterTypes());
        request.setParameters(args);
        return networkClient.request(request).getData();
    }
}
